<?php
namespace App\Http\Controllers\IM;

use App\Http\Controllers\Controller;
use App\Libraries\Decorator\Image\CoverDecorator;
use App\Libraries\Easemob\Easemob;
use App\Models\IM\Group;
use App\Models\User\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use OSS\Core\OssException;
use OSS\OssClient;


class IMController extends Controller{

    protected $easemob;
    protected $cover_decorator;

    public function __construct(CoverDecorator $cover){
        $this->easemob = Easemob::singleton();
        $this->cover_decorator = $cover;
    }

    /**
     * 好友列表
     * @param User $users
     * @return \Illuminate\Http\JsonResponse
     */
    public function friends(User $users){
        $user = Auth::user();
        $friends = $this->easemob->showFriends($user->user_id);
        if(isset($friends['error'])){
            return $this->sendSuccessResponse([]);
        }
        $users->addDecorator($this->cover_decorator);
        if(!is_array($friends['data'])){
            $friends['data'] = [];
        }
        $friends['data'] = array_merge($friends['data'], ['3','4','5','6','7','8']);
        $data = $users->getUserListByUserId($friends['data']);
        return $this->sendSuccessResponse($data);
    }

    /**
     * 用户所有的群
     * @param User $user
     * @param Group $group
     * @return \Illuminate\Http\JsonResponse
     */
    public function allGroups(User $user, Group $group){
        $rs = [];
        $groups = Easemob::singleton()->getGroupsForUser(Auth::id());
        if(isset($groups['error'])){
            return $this->sendFailResponse(400, 40400);
        }
        $user->addDecorator($this->cover_decorator);
        $group->addDecorator($this->cover_decorator);
        foreach($groups['data'] as $k => $v){
            if($v['groupname'] == '未命名'){
                continue;
            }
            $tmp['groupid'] = $v['groupid'];
            $tmp['groupname'] = $v['groupname'];
            $group_data = $group->getGroup($v['groupid']);
            $tmp['cover'] = empty($group_data['cover'])?'':$group_data['cover'];
            $rs['list'][] = $tmp;
        }
        return $this->sendSuccessResponse($rs);
    }

    /**
     * 单个群组成员
     * @param User $user
     * @param $id
     * @param Group $group
     * @return \Illuminate\Http\JsonResponse
     */
    public function groupMembers(User $user, $id, Group $group){
        $validator = Validator::make([
            'id' => $id,
        ], [
            'id' => 'required|integer',
        ], [
            'id.required' => '10001',
            'id.integer' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }

        $members = $this->easemob->getGroupUsers($id);
        if(isset($members['error'])){
            return $this->sendFailResponse(400, 40400);
        }
        $user->addDecorator($this->cover_decorator);
        $group->addDecorator($this->cover_decorator);
        if(!is_array($members['data'])){
            return $this->sendFailResponse(400, 40400);
        }
        $data = [];
        foreach($members['data'] as $v){
            $data['members'][] = isset($v['member'])?$v['member']:$v['owner'];
            if(isset($v['owner'])){
                $data['owner_id'] = $v['owner'];
            }
        }
        $rs['list'] = $user->getUserListByUserId($data['members']);
        $rs['owner_id'] = $data['owner_id'];
        $group_data = $group->getGroup($id);
        $rs['cover'] = empty($group_data['cover'])?'':$group_data['cover'];
        return $this->sendSuccessResponse($rs);
    }

    /**
     * 创建/修改群
     * @param Group $group
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addGroup(Group $group, Request $request){
        $validator = Validator::make($request->all(), [
            'group_id' => 'required|integer',
            'cover' => 'image',
        ], [
            'group_id.required' => '10001',
            'group_id.integer' => '10002',
            'cover.image' => '10003',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }
        $ossClient = new OssClient(env('ALIYUN_ID'), env('ALIYUN_KEY'), env('ALIYUN_ENDPOINT'));
        $bucket = env('ALIYUN_BUCKET');
        try{
            $group = $group->firstOrCreate(['group_id'=>$request['group_id']]);
            if($request->hasFile('cover') && $request->file('cover')->isValid()){
                $object = 'image/'.uniqid().'.'.$request->file('cover')->extension();
                $ossClient->uploadFile($bucket, $object, $request->file('cover')->getFileInfo());
                $group->cover = $object;
            }
            $group->save();
            $group->addDecorator($this->cover_decorator);
            $group = $group->after($group);
            return $this->sendSuccessResponse($group);
        }catch (OssException $e){
            return $this->sendFailResponse(400,40003);
        }catch(\Exception $e){
            return $this->sendFailResponse(500,50000);
        }
    }

}